package com.atguigu.flink08;

import com.atguigu.beans.WaterSensor;
import com.atguigu.func.WaterSensorMapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Felix
 * @date 2024/2/27
 * 该案例 演示检测每种传感器的水位值，如果连续的两个水位差值超过10，就输出报警
 * 错误思路
 */
public class Flink02_State_ValueState_1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> wsDS = env
                .socketTextStream("hadoop102", 8888)
                .map(new WaterSensorMapFunction());

        wsDS
                .keyBy(WaterSensor::getId)
                .process(
                        new KeyedProcessFunction<String, WaterSensor, String>() {
                            //注意：这种写法是有问题的，同一个并行度的多个组，会共享该变化
                            //Integer lastVc = 0;
                            Map<String, Integer> lastVcMap = new HashMap<>();

                            @Override
                            public void processElement(WaterSensor ws, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                                Integer curVc = ws.vc;
                                //获取当前传感器的上次水位值
                                String id = ctx.getCurrentKey();
                                Integer lastVc = lastVcMap.get(id) == null ? 0 : lastVcMap.get(id);

                                if (Math.abs(curVc - lastVc) > 10) {
                                    out.collect("传感器id" + id + "的当前水位值" + curVc + "和上一个水位值" + lastVc + "差大于10");
                                }

                                lastVcMap.put(id,curVc);
                            }
                        }
                ).printToErr();

        env.execute();
    }
}
